//
//  VerifyCodeInputView.swift
//  Exchange
//
//  Created by rui on 2018/4/25.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class InputLabel: UILabel {
    
    var isSelected: Bool! {
        didSet {
            self.layer.borderWidth = 0.5
            var selectedColor = kHighGrayColor.cgColor
            var normalColor = kGrayColor.cgColor
            if ThemeManager.default.currentThemeMode() == .night {
                selectedColor = kGrayColor.cgColor
                normalColor = kHighGrayColor.cgColor
            }
            if isSelected  {
                self.layer.borderColor = selectedColor
            }else {
                self.layer.borderColor = normalColor
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initUI()
    }
    
    func initUI() {
        self.isSelected = false
        self.themeTextColor = ThemeManager.ThemeColorKeys.text1
        self.textAlignment = .center
        self.font = UIFont.systemFont(ofSize: 17)
        self.layer.cornerRadius = 5
        self.layer.masksToBounds = true
        self.isUserInteractionEnabled = false
    }
}

class VerifyCodeInputView: UIView,UITextViewDelegate {

    @IBInspectable var inputCount: Int = 6 {
        didSet {
            initUI()
        }
    }
    
    var isSecurity = false
    
    @IBInspectable var inputSize = CGSize(width: 40, height: 40)
    
    typealias VerifyCodeDidChange = (String)->()
    
    var text: String? {
        get {
            return textView.text
        }
        set {
            textView.text = newValue
            self.textViewDidChange(textView)
        }
    }
    
    var verifyCodeChange: VerifyCodeDidChange?
    
    
    private var labels = [InputLabel]()
    
    private var textView: UITextView = {
        let textView = UITextView()
        textView.tintColor = UIColor.clear
        textView.backgroundColor = UIColor.clear
        textView.textColor = UIColor.clear
        textView.keyboardType = .numberPad
        return textView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initUI()
    }
    
    func initUI() {
        for subView in self.subviews {
            subView.removeFromSuperview()
        }
        labels.removeAll()
        textView.delegate = self
        self.addSubview(textView)
        for index in 0..<inputCount {
            let lbl = InputLabel()
            lbl.isSelected = index == 0
            labels.append(lbl)
            self.addSubview(lbl)
        }
        let ges = UITapGestureRecognizer(target: self, action: #selector(beginEdit))
        self.addGestureRecognizer(ges)
        beginEdit()
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let xGap = (self.frame.width - inputSize.width * CGFloat(inputCount)) / CGFloat(inputCount - 1)
        let yGap = (self.frame.height - inputSize.height) * 0.5
        var lbl: UILabel
        for index in 0..<labels.count {
            lbl = labels[index]
            lbl.frame = CGRect(x: CGFloat(index) * (inputSize.width + xGap), y: yGap, width: inputSize.width, height: inputSize.height)
        }
    }
    
    func textViewDidChange(_ textView: UITextView) {
        
        guard let text = textView.text else {
            return
        }
        if text.count > inputCount {
            let subString = String(text.prefix(inputCount))
            textView.text = subString
        }
        if text.count >= inputCount {
            endEdit()
        }
        
        let strs = text.map { (c) -> String in
            return String(c)
        }
        var lbl: InputLabel
        for index in 0..<inputCount {
            lbl = self.labels[index]
            lbl.isSelected = strs.count == index
            if index < strs.count {
                if isSecurity {
                    lbl.text = "●"
                }else {
                    lbl.text = strs[index]
                }
            }else {
                lbl.text = ""
            }
        }
        verifyCodeChange?(textView.text)
    }

    @objc func beginEdit() {
        textView.becomeFirstResponder()
    }
    
    func endEdit() {
        textView.resignFirstResponder()
    }
    
    deinit {
        endEdit()
    }
}
